package com.codechuan.didi_hack.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.codechuan.didi_hack.common.Constant;
import com.codechuan.didi_hack.databinding.FragmentHomeBinding;
import com.codechuan.didi_hack.entity.SysCarInfo;
import com.codechuan.didi_hack.thread.MainStartThread;
import com.codechuan.didi_hack.utils.DiDiHttpUtil;
import com.codechuan.didi_hack.utils.DialogUtil;

public class HomeFragment extends Fragment implements View.OnClickListener {

    private FragmentHomeBinding binding;
    private Button startGetOrder;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        // 获取抢单按钮并设置点击事件
        startGetOrder = binding.startGetOrder;
        startGetOrder.setOnClickListener(this);
        if (Constant.isStart)
            startGetOrder.setText("停止抢单");
        if (!Constant.isStart)
            startGetOrder.setText("开始抢单");
        return binding.getRoot();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onClick(View view) {
        if (binding.startGetOrder.getId() == view.getId()) {
            if (Constant.isStart) {
                DialogUtil.showDialog(getContext(), "关闭算法中,请等待");
                Constant.isStart = false;
                try {
                    // 延迟三秒避免内存泄露
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                startGetOrder.setText("开始抢单");
            } else {
                // 获取车辆主号信息
                Constant.executorService.execute(() -> Constant.CAR_INFO = DiDiHttpUtil.getDriverVehicleInformation(Constant.token.get(0)));
                // 执行刷单线程
                Constant.executorService.execute(new MainStartThread());
                startGetOrder.setText("停止抢单");
                Constant.isStart = true;
            }
        }
    }
}